package storage

import (
	"fmt"
	"github.com/mrminglang/tools/uuids"
	"os"
	"path/filepath"
)

var Storage *storageStr

type storageStr struct {
	// public 目录的文件夹路径
	AbsPath  string
	DiskName string
	Uri      string
}

// RootPath 获取项目路径
func RootPath() string {
	dir, err := os.Getwd()
	if err != nil {
		return ""
	}
	for {
		if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
			return dir
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			return ""
		}
		dir = parent
	}
}

// StoragePath 获取storage路径
func GetStoragePath() string {
	return filepath.Join(RootPath(), "storage")
}

// Init 初始化
func Init(storagePath string) {
	storage := new(storageStr)
	storage.AbsPath = storagePath

	Storage = storage
}

// FullPath 获取绝对路径
func (s *storageStr) FullPath(path string) string {
	return filepath.Join(s.AbsPath, path)
}

// GetExcelPath 获取Excel文件的绝对路径absolutePath和相对路径relativePath
func (s *storageStr) GetExcelPath(path string, name string) (string, string) {
	fullPath := s.FullPath(path)
	if name == "" {
		name = uuids.GetRandowUUID()
	}
	fileName := fmt.Sprintf("%s.xlsx", name)
	filePath := filepath.Join(fullPath, fileName)
	err := os.MkdirAll(fullPath, os.ModePerm)
	if err != nil {
		return "", ""
	}

	return filePath, filepath.Join(path, fileName)
}

// GetPath 获取Excel文件的绝对路径absolutePath和相对路径relativePath
func (s *storageStr) GetPath(path string, fileName string) (string, string) {
	fullPath := s.FullPath(path)
	filePath := filepath.Join(fullPath, fileName)
	err := os.MkdirAll(fullPath, os.ModePerm)
	if err != nil {
		return "", ""
	}

	return filePath, filepath.Join(path, fileName)
}

// 获取绝对路径
func (s *storageStr) GetAbsolutePath(path string, fileName string) string {
	fullPath := s.FullPath(path)
	filePath := filepath.Join(fullPath, fileName)
	err := os.MkdirAll(fullPath, os.ModePerm)
	if err != nil {
		return ""
	}

	return filePath
}
